package 替换子串得到平衡字符串;

/**
 * @Program:IntelliJ IDEA
 * @description:
 * @author:香蕉你个啵娜娜 l.h-p@qq.com
 * @create:2023-02-13 20:30
 **/

public class Solution {
    public int balancedString(String S) {
        char[] str = S.toCharArray();
        int[] cnt = new int['X'];
        for (char c : str) {
            ++cnt[c];
        }
        int n = str.length, m = n/4;
        if (cnt['Q'] == m && cnt['W'] == m && cnt['E'] == m && cnt['R'] == m) {
            return 0;
        }
        int ans = 0, left = 0;
        for (int right = 0; right < n; right++) {
            --cnt[str[right]];
            while (cnt['Q'] <= m && cnt['W'] <= m && cnt['E'] <=m && cnt['R'] <= m) {
                ans = Math.min(ans, right - left + 1);
                ++cnt[str[left++]];
            }
        }
        return ans;
    }
}
